package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"sync"

	"github.com/gorilla/mux"
)

var (
	tcpConn    net.Conn
	tcpConnMux sync.Mutex
	carTCPAddr = "192.168.137.24:6000"
)

func main() {
	InitDB()
	wsURL := "ws://localhost:8080"
	cmd := "$01130601C8E3#"

	if err := sendWebSocketCommand(wsURL, cmd); err != nil {
		log.Fatal("发送失败:", err)
	}

	// err := connectToCarTCP()
	// if err != nil {
	// 	log.Fatalf("连接小车TCP失败: %v", err)
	// }

	r := mux.NewRouter()

	// 注册设备影子接口路由
	registerShadowRoutes(r)
	// 注册报警管理接口和 WebSocket 路由
	registerAlertRoutes(r)

	fmt.Println("服务启动，监听端口8088")
	log.Fatal(http.ListenAndServe(":8088", r))
}

func connectToCarTCP() error {
	tcpConnMux.Lock()
	defer tcpConnMux.Unlock()

	conn, err := net.Dial("tcp", carTCPAddr)
	if err != nil {
		return err
	}

	tcpConn = conn
	log.Println("成功连接小车TCP:", carTCPAddr)

	// 可以额外启动一个协程持续监听小车TCP回传数据
	go func() {
		buf := make([]byte, 1024)
		for {
			n, err := tcpConn.Read(buf)
			if err != nil {
				log.Println("小车TCP连接读取错误:", err)
				return
			}
			log.Printf("[小车反馈] %s\n", string(buf[:n]))
		}
	}()

	return nil
}
